class Account < ActiveRecord::Base
  belongs_to :owner
  has_many :transactions
  validates_presence_of :account_status

  def close
    update_attribute :is_removed, 1
  end

  def ban
    update_attribute :is_banned, 1
  end
  
  def get_avaiable_sum
    balance - blocked_summ
  end

  def self.move_funds(from, to, amount)
    acc = find(from)
    return nil if acc.is_banned || acc.is_removed
    return nil if acc.account_status != "credit" && acc.get_avaiable_sum < amount
    transaction do
      update_counters from, :balance => -amount
      update_counters to, :balance => amount
      transaction = Transaction.new :from_id => from, :to_id => to, :summa => amount
      transaction.save!
      transaction.id
    end
  end
  
  def self.block_amount(service_id, account_id, amount, is_fact = false, details = '')
    return false if !is_fact && find(account_id).get_avaiable_sum < amount
    transaction do
      update_counters account_id, :blocked_summ => amount
      block = Block.new :account_id => account_id, :summa => amount, :is_open => 1, 
                :service_id => service_id, :close_time => nil, :transaction_id => nil,
                :details => details, :is_fact => is_fact
      block.save!
      block.id
    end
  end

end
